﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace CapsBeep
{
    class KeyboardWatcher
    {
        public class KeyboardEventArgs : EventArgs
        {
            public bool NotifyCapsLock { get; set; }
            public bool NotifyNumLock { get; set; }
            public bool IsNotify { get { return NotifyNumLock || NotifyCapsLock; } }
        }

        public static event EventHandler<KeyboardEventArgs> KeyboardEvent;

        private static bool _watchNumLock;
        public static bool WatchNumLock
        {
            get
            {
                return _watchNumLock;
            }
            set
            {
                if (value != _watchNumLock)
                {
                    _watchNumLock = value;
                    UpdateHook();
                }
            }
        }

        private static bool _watchCapsLock;
        public static bool WatchCapsLock
        {
            get 
            { 
                return _watchCapsLock;
            }
            set 
            {
                if (value != _watchCapsLock)
                {
                    _watchCapsLock = value;
                    UpdateHook();
                }
            }
        }

        private static void UpdateHook()
        {
            if (_watchNumLock || _watchCapsLock)
                SetHook(_proc);
            else
                Unhook();
        }

        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;

        private static LowLevelKeyboardProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;


        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private static void Unhook()
        {
            UnhookWindowsHookEx(_hookID);
        }

        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                int scanCode = Marshal.ReadInt32(lParam, sizeof(Int32));
                int flags = Marshal.ReadInt32(lParam, 2 * sizeof(Int32));

                KeyboardEventArgs args = new KeyboardEventArgs();

                if (_watchCapsLock)
                {
                    if (Control.IsKeyLocked(Keys.CapsLock))
                    {
                        // 0x41 to 0x5A - A-Z
                        if ((vkCode >= 0x41) && (vkCode <= 0x5A))
                            args.NotifyCapsLock = true;
                    }
                    else
                    {
                        // Caps Lock key pressed ON
                        if (vkCode == 0x14)
                            args.NotifyCapsLock = true;
                    }
                }

                // 0x60 to 0x69 - NumPad0-NumPad9
                if (_watchNumLock)
                {
                    if (!Control.IsKeyLocked(Keys.NumLock))
                    {
                        if ((vkCode >= 0x60) && (vkCode <= 0x69))
                            args.NotifyNumLock = true;

                        // 0x21 to 0x2E - INS, DEL, PGUP, etc... (plus a few extras like print screen)
                        if ((vkCode >= 0x21) && (vkCode <= 0x2E))
                            args.NotifyNumLock = true;
                    }
                    else
                    {
                        // Num Lock key pressed ON
                        if (vkCode == 0x90)
                            args.NotifyNumLock = true;
                    }
                }

                if (args.IsNotify)
                    KeyboardEvent(null, args);              
            }

            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

    }
}
